<!-- 库区库位编辑弹窗 -->
<template>
  <ele-modal form :width="460" :model-value="modelValue" title="批量新增库区库位" @update:model-value="updateModelValue">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="库区类型" prop="type">
        <el-select v-model="form.type" clearable placeholder="请选择类型">
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="库区名称" prop="name">
        <el-input v-model="form.name" clearable :maxlength="20" placeholder="请输入库区库位名称" />
      </el-form-item>
      <el-form-item label="货架数量" prop="h_num">
        <el-input v-model.number="form.h_num" :formatter="value => value.replace(/[^\d]/g, '')" placeholder="请输入货架数量" />
      </el-form-item>
      <el-form-item label="层数数量" prop="c_num">
        <el-input v-model.number="form.c_num" :formatter="value => value.replace(/[^\d]/g, '')" placeholder="请输入层数数量" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  warehouseId: Number,
  typeList: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['done', 'update:modelValue'])

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)

/** 表单数据 */
const [form, resetFields] = utils.useFormData({
  name: '',
  type: undefined,
  h_num: '',
  c_num: '',
})

/** 表单验证规则 */
const rules = reactive({
  type: {
    required: true,
    message: '请选择库区类型',
    trigger: 'change',
  },
  name: {
    required: true,
    message: '请输入库区库位名称',
    trigger: 'blur',
  },
  h_num: {
    required: true,
    type: 'number',
    min: 1,
    message: '请输入货架数量',
    trigger: 'blur',
  },
  c_num: {
    required: true,
    type: 'number',
    min: 1,
    message: '请输入层数数量',
    trigger: 'blur',
  },
})

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true
    utils.post('/warehouseLocation/batchAdd', { ...form, warehouse_id: props.warehouseId })
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          updateModelValue(false)
          emit('done')
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (modelValue) {
      resetFields()
      formRef.value?.clearValidate?.()
      if (props.typeList.length) {
        form.type = props.typeList[0].id
      }
    }
  },
)
</script>
